package com.example.demo.service;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

@Component  
public class Consumer {  
        // 使用JmsListener配置消费者监听的队列，其中text是接收到的消息  
	private  final String  test= "mytest.queue";
    @JmsListener(destination = test)  
    public void receiveQueue(String text) {  
    	ConnectionFactory connectionFactory;
    	Connection connection = null;//连接
    	Session session;//会话
    	Destination destination;//连接目的地
    	MessageConsumer messageConsumer;
    	connectionFactory=new ActiveMQConnectionFactory("","","127.0.0.1:61616");
        try {
            connection=connectionFactory.createConnection();
            connection.start();//启动连接
            session=connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
            destination=session.createTopic("mytest.queue");
            messageConsumer=session.createConsumer(destination);
            while(true) {
                messageConsumer.setMessageListener(new MessageListener(){  
                    @Override  
                    public void onMessage(Message m) {  
                        TextMessage textMsg = (TextMessage) m;  
                        try {  
                            System.out.println(textMsg.getText());  
                        } catch (JMSException e) {  
                            e.printStackTrace();  
                        }  
                    }  
                     
                });
            }
        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
              try {
                if (null != connection) {
                    connection.close();
                }
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("Consumer收到的报文为:"+text);  
    }  
}  
